<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<div th:fragment="content">
    <!-- SQL配置 -->
    <div class="page-header"></div>

    <!-- 已添加的SQL配置 -->
    <div class="form-group">
        <label class="col-sm-2 control-label">SQL表</label>
        <div class="col-sm-4">
            <select id="sqlTableSelect" class="form-control select-control">
                <option th:each="sqlTable,state:${connector?.config?.sqlTables}" th:text="${sqlTable?.sqlName}" />
            </select>
        </div>
        <div class="col-sm-6 text-right">
            <button id="delSqlTableBtn" type="button" class="btn btn-default hidden"> <span class="fa fa-remove"></span>删除</button>
            <button id="editSqlTableBtn" type="button" class="btn btn-default hidden"> <span class="fa fa-pencil"></span>修改</button>
            <button id="addSqlTableBtn" type="button" class="btn btn-primary"> <span class="fa fa-plus"></span>添加(<span id="sqlTableCount">[[${connector?.config?.sqlTables?.size()} ?: 0]]</span>)</button>
        </div>
        <input type="hidden" id="sqlTableParams" name="sqlTableParams"/>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">SQL名称</label>
        <div class="col-sm-4">
            <input class="form-control" id="sqlName" type="text" maxlength="32" placeholder="ERP用户表"/>
        </div>
        <label class="col-sm-2 control-label">主表 <i class="fa fa-question-circle fa_gray" aria-hidden="true" title="用于增量同步，根据监听的主表获取增量数据"></i></label>
        <div class="col-sm-4">
            <input class="form-control" id="table" type="text" maxlength="32" placeholder="USER"/>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-12 text-right">
            <a href="javascript:beautifySql();"><span class="fa fa-magic fa-1x fa-flip-horizontal dbsyncer_pointer" title="美化SQL"></span>美化SQL</a>
        </div>
    </div>

<script type="text/javascript" th:inline="javascript">
    $(function () {
        let sqlTables = [[${connector?.config?.sqlTables}]];
        // SQL配置模板
        let $template = {
            selector: initSelectIndex($("#sqlTableSelect"), 1),
            addSqlTableBtn: $("#addSqlTableBtn"),
            editSqlTableBtn: $("#editSqlTableBtn"),
            delSqlTableBtn: $("#delSqlTableBtn"),
            sqlTableCount: $("#sqlTableCount"),
            sqlTableParams: $("#sqlTableParams"),
            sqlTableArray: sqlTables == null ? [] : sqlTables,
            sqlNameInput: $("#sqlName"),
            tableInput: $("#table"),
            sqlInput: $("#sql"),
            // 禁用按钮
            before: function ($btn) {
                $btn.prop('disabled', true);
            },
            // 校验表单
            validate: function (callback) {
                let itemSqlName = this.validateItem(this.sqlNameInput, "SQL名称不能空.");
                if (!itemSqlName) {
                    return;
                }
                let itemTable = this.validateItem(this.tableInput, "主表不能空.");
                if (!itemTable) {
                    return;
                }
                let itemSql = this.validateItem(this.sqlInput, "SQL不能空.");
                if (!itemSql) {
                    return;
                }
                callback();
            },
            // 校验参数
            validateItem: function ($input, $msg) {
                if (isBlank($input.val())) {
                    bootGrowl($msg, "danger");
                    return false;
                }
                return true;
            },
            // 加入新项到下拉
            addOption: function () {
                let sqlName = this.sqlNameInput.val();
                this.sqlTableArray.push({"sqlName": sqlName, "table": this.tableInput.val(), "sql": this.sqlInput.val()});
                this.selector.append('<option>' + sqlName + '</option>');
                this.selector.selectpicker('refresh');
                this.selector.selectpicker('val', sqlName);
                this.stash();
            },
            // 删除下拉选中项
            removeOption: function () {
                this.removeSqlTable(this.selectedVal());
                this.selector.find('option:selected').remove();
                this.selector.selectpicker('refresh');
                this.stash();
            },
            // 暂存配置
            stash: function () {
                this.sqlTableParams.val(JSON.stringify(this.sqlTableArray));
            },
            // 清空表单
            clear: function () {
                this.sqlNameInput.val('');
                this.tableInput.val('');
                this.sqlInput.val('');
            },
            // 显示默认配置
            popStash: function(){
                if (this.hasOption()) {
                    this.selector.selectpicker('val', this.sqlTableArray[0].sqlName);
                }
            },
            // 回显下拉选中配置
            apply: function () {
                let sqlTable = this.getSqlTable(this.selectedVal());
                if (sqlTable != null) {
                    this.sqlNameInput.val(sqlTable.sqlName);
                    this.tableInput.val(sqlTable.table);
                    this.sqlInput.val(sqlTable.sql);
                }
                this.reset();
            },
            // 显示操作菜单
            showMenu: function () {
                if (this.hasOption()) {
                    this.editSqlTableBtn.removeClass("hidden");
                    this.delSqlTableBtn.removeClass("hidden");
                } else {
                    this.editSqlTableBtn.addClass("hidden");
                    this.delSqlTableBtn.addClass("hidden");
                }
            },
            // 更新添加按钮数量显示
            refreshCount: function () {
                this.sqlTableCount.text(this.sqlTableArray.length);
            },
            // 是否有配置
            hasOption: function () {
                return this.sqlTableArray.length > 0;
            },
            // 下拉选择值
            selectedVal: function () {
                return this.selector.selectpicker('val');
            },
            // 清空美化记录
            reset: function () {
                this.sqlInput.removeAttr('tmp');
            },
            // 恢复按钮
            after: function ($btn) {
                $btn.removeAttr('disabled');
            },
            getSqlTable: function (sqlName) {
                if (!isBlank(sqlName)) {
                    let tLen = this.sqlTableArray.length;
                    for (let j = 0; j < tLen; j++) {
                        if (this.sqlTableArray[j].sqlName == sqlName) {
                            return this.sqlTableArray[j];
                        }
                    }
                }
                return null;
            },
            removeSqlTable: function (sqlName) {
                let newArray = [];
                if (!isBlank(sqlName)) {
                    let tLen = this.sqlTableArray.length;
                    for (let j = 0; j < tLen; j++) {
                        if (this.sqlTableArray[j].sqlName != sqlName) {
                            newArray.push(this.sqlTableArray[j]);
                        }
                    }
                }
                this.sqlTableArray = newArray;
            }
        }

        $template.showMenu();
        $template.selector.on('changed.bs.select', function () {
            $template.apply();
        });
        $template.stash();
        $template.popStash();
        bindSqlTableAddEvent($template);
        bindSqlTableEditEvent($template);
        bindSqlTableDelEvent($template);
    })

    function bindSqlTableAddEvent($template) {
        $template.addSqlTableBtn.click(function () {
            $template.before($(this));
            $template.validate(function () {
                // 重复校验
                let newSqlName = $template.sqlNameInput.val();
                let sqlTable = $template.getSqlTable(newSqlName);
                if (sqlTable != null) {
                    bootGrowl(newSqlName + " 已存在.", "danger");
                } else {
                    $template.addOption();
                    $template.refreshCount();
                    $template.showMenu();
                }
            });
            $template.reset();
            $template.after($(this));
        });
    }
    function bindSqlTableEditEvent($template) {
        $template.editSqlTableBtn.click(function () {
            $template.before($(this));
            $template.validate(function () {
                let oldSqlName = $template.selectedVal();
                if (!isBlank(oldSqlName)) {
                    let newSqlName = $template.sqlNameInput.val();
                    // 重命名的SQL名称已存在
                    if (oldSqlName != newSqlName && $template.getSqlTable(newSqlName) != null) {
                        bootGrowl(newSqlName + " 已存在.", "danger");
                        return;
                    }
                    $template.removeOption();
                    $template.addOption();
                } else {
                    bootGrowl("修改无效.", "danger");
                }
            });
            $template.reset();
            $template.after($(this));
        });
    }
    function bindSqlTableDelEvent($template) {
        $template.delSqlTableBtn.click(function () {
            $template.before($(this));
            $template.removeOption();
            $template.refreshCount();
            $template.clear();
            $template.showMenu();
            $template.popStash();
            $template.reset();
            $template.after($(this));
        });
    }
</script>
</div>
</html>